import { compileToFunction } from "./compile/index"
import { initState } from "./initState"
import { callHook, mountComponents } from "./lifecycle"
import { mergeOptions } from "./utils/index"

export function initMixin(Vue) {
  Vue.prototype._init = function(options) {
    let vm = this
    vm.$options = mergeOptions(Vue.options, options)
    callHook(vm, 'beforeCreated')
    // 初始化状态
    initState(vm)

    callHook(vm, 'created')
    // 渲染模版
    if(vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }

  // 创建$mount
  Vue.prototype.$mount = function(el) {
    // el template render
    let vm = this
    el = document.querySelector(el)
    vm.$el = el
    let options = vm.$options
    if(!options.render) {
      let template = options.template
      if(!template && el) {
        // 获取html
        el = el.outerHTML
        let render = compileToFunction(el)
        // （1）将render 函数变成vnode  (2) vnode 变成这是DOM
        options.render = render
      }
    }
    // 挂载组件
    mountComponents(vm, el)
  }
}
